package pri.damai.xiaowu.anydoor.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import pri.damai.xiaowu.anydoor.netty.codec.BizModelDecoder;
import pri.damai.xiaowu.anydoor.netty.codec.BizModelEncoder;
import pri.damai.xiaowu.anydoor.business.ModelHolder;
import pri.damai.xiaowu.anydoor.netty.HandlerHolder;

import java.io.IOException;

/**
 * Netty 客户端
 *
 * @description
 * @author YangXinFu
 * @date 10:09 2022/7/25
 **/
public class NettyClient {

    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        ModelHolder.initModel();
        System.out.println(HandlerHolder.dataModelMap);
        new NettyClient().bind(4466);
    }

    private void bind(int port) {
        // 配置服务端 NIO 线程组
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.AUTO_READ,true)
                .handler(new ChannelInitializer<SocketChannel>(){
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 5, 4));
                        channel.pipeline().addLast(new BizModelDecoder());
                        channel.pipeline().addLast(new ClientChatHandler());
                        channel.pipeline().addLast(new BizModelEncoder());
                    }
                });


        ChannelFuture sync = null;
        try {
            sync = bootstrap.connect("127.0.0.1",port).sync();
            System.out.println("Netty Client启动完毕。");

            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }


    }
}
